import * as THREE from 'three'
import gsap from 'gsap'
import vertexShader from '@/shader/FlyLine/vertex.glsl'
import fragmentShader from '@/shader/FlyLine/fragment.glsl'

export default class FlyLineShader {
  constructor(position = { x: -1.8, z: 3 }, color = 0xffff00) {
    //1、生成曲线
    let linePoints = [
      new THREE.Vector3(0, 0, 0),
      new THREE.Vector3(position.x / 2, 4, position.z / 2),
      new THREE.Vector3(position.x, 0, position.z),
    ]
    // 1、创建曲线
    this.linecurve = new THREE.CatmullRomCurve3(linePoints)
    const points = this.linecurve.getPoints(1000)
    // 2、创建几何体
    this.geometry = new THREE.BufferGeometry().setFromPoints(points)

    //给每个顶点设置属性
    const aSizeArr = new Float32Array(points.length)

    for (let i = 0; i < points.length; i++) {
      aSizeArr[i] = i
    }

    // 设置几何体顶点属性
    this.geometry.setAttribute('aSize', new THREE.BufferAttribute(aSizeArr, 1))

    // 3、设置着色器材质
    this.shaderMaterial = new THREE.ShaderMaterial({
      uniforms: {
        uTime: { value: 0 },
        uColor: { value: new THREE.Color(color) },
        uLength: { value: points.length },
      },
      vertexShader,
      fragmentShader,
      transparent: true,
      depthWrite: false,
      blending: THREE.AdditiveBlending,
    })

    this.mesh = new THREE.Points(this.geometry, this.shaderMaterial)

    // 改变动画
    gsap.to(this.shaderMaterial.uniforms.uTime, {
      value: 1000,
      duration: 2,
      repeat: -1,
      ease: 'none',
    })
  }
  remove() {
    this.mesh.remove()
    this.mesh.removeFromParent()
    this.mesh.geometry.dispose()
    this.mesh.material.dispose()
  }
}
